package com.bootdo.api.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求响应信息工具类
 * 
 * @author Administrator
 *
 */
public class RequestAndResponseUtil {

	/**
	 * 将数据流转换为对象
	 * @param inputStream
	 * @param beanCalss
	 * @return
	 */
	public static <T> T inputStreamToBean(HttpServletRequest request, Class<T> beanCalss) {
		StringBuffer buf = new StringBuffer();
		BufferedReader br;
		T bean = null;
		try {
			InputStream stream = request.getInputStream();
			br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
			String line;
			while (null != (line = br.readLine())) {
				buf.append(line).append("\n");
			}
			bean = (T) JsonPluginsUtil.jsonToBean(buf.toString(), beanCalss);
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return bean;
	}

	
	/**
	 * 从一个map 对象中得到一个java对象
	 * 
	 * @param map
	 * @param beanCalss
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static <T> T mapToBean(Map<String, Object> map, Class<T> beanCalss) {
		T bean = null;
		try {
			bean = beanCalss.newInstance();
			if (bean == null) {
				throw new Exception();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 处理map的key
		Map<String, Object> newmap = new HashMap<String, Object>();
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			newmap.put("set" + entry.getKey().trim().toLowerCase(), entry.getValue());
		}
		// 进行值装入
		Method[] ms = beanCalss.getMethods();
		for (Method method : ms) {
			String mname = method.getName().toLowerCase();
			if (mname.startsWith("set")) {

				Class[] cla = method.getParameterTypes();
				Object v = newmap.get(mname);

				if (v != null && cla.length == 1) {
					try {
						method.invoke(bean, v);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return bean;
	}
	
}
